<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
use DB;
use Hash;

class LoginController extends Controller
{
    //login
    public function login(Request $request)
    {
    	if($request -> isMethod('post'))
    	{
    		$this -> validate($request,[
    			'email' => 'required|email',
    			'password' => 'required',
    			'captcha' => 'required'
    			],[
    			'email.required' => '请输入邮箱',
    			'email.email' => '邮箱格式不正确',
    			'password.required' => '密码不能为空',
    			'captcha.required' => '验证码不能为空'
    			]);
    		$data = $request -> except('_token');
    		$c = Session::get('milkcaptcha');

    		//验证码
    		if($c != $data['captcha'])
    		{
    			$request -> flash();
    			return back() -> with('验证码错误');
    		}
    		$res = DB::table('users') -> where('email',$data['email']) -> first();

    		//验证邮箱
    		if($data['email'] != $res -> email)
    		{
    			return back() -> with('邮箱不正确');
    		}
    		//密码验证
    		$r = Hash::check($data['password'], $res -> password);
    		if(!$r)
    		{
    			$request -> flash();
    			return back() -> with('用户名或密码错误');
    		}

    		Session::set('master', $res);
    		return redirect('/admin/index') -> with(['info' =>'登录成功']);
    	}
    	return view('admin.login');
    }

    //退出
    public function logout()
    {
    	Session::forget('master');
    	return redirect('/admin/login') -> with(['info' => '退出成功']);
    }

}
